//
// Created by work on 24-7-5.
//

#include "os/miscellany/CConfigs.h"

namespace iotplat {
    CConfigs &CConfigs::ins() {
        static CConfigs cfg;
        return cfg;
    }

    CConfigs::CConfigs() : doc(std::make_shared<XMLDocument>()), root(nullptr) {
        const char* path = std::getenv("IOT_PLAT");
        if (!path) {
            std::cerr << "The environment variable IOT_PLAT is not set." << std::endl;
            return;
        }

        XMLError error = doc->LoadFile((std::string(path)+"/cfg.xml").c_str());
        if (error != XML_SUCCESS) {
            std::cerr << "Failed to load XML file: " << path << ". Error: " << error << std::endl;
            return;
        }

        root = doc->FirstChildElement("root");
        if(!root) {
            std::cerr << "root set faild: " << path << ". Error: " << error << std::endl;
            return;
        }
    }

    CConfigs::SDataBaseCfg CConfigs::dateBaseCfg(CConfigs::EDateBase type) {
        SDataBaseCfg cfg;
        switch (type) {
            case EPlat:{
                int port;
                XMLElement * ele = root->FirstChildElement("database");
                const tinyxml2::XMLAttribute* attr = ele->FirstAttribute();
                while (attr != nullptr) {
                    if (std::string("ip") == attr->Name()) {
                        cfg.ip = attr->Value();
                    } else if (std::string("port") == attr->Name()) {
                        cfg.port = static_cast<short int>(std::stoi(attr->Value()));
                    } else if (std::string("engine") == attr->Name()) {
                        cfg.engine = attr->Value();
                    } else if (std::string("lib") == attr->Name()) {
                        cfg.lib = attr->Value();
                    } else if (std::string("username") == attr->Name()) {
                        cfg.username = attr->Value();
                    } else if (std::string("password") == attr->Name()) {
                        cfg.password = attr->Value();
                    }
                    attr = attr->Next();
                }
            }break;


            default:
                break;
        }

        return cfg;
    }
} // iotplat